package com.lecoboy.highconcurrency.lockdemo;

import java.util.HashMap;
import java.util.Map;

/**
 * 读写锁测试和 HashMap非线程安全测试
 */
public class CacheAndHashMapTest {

    public static void main(String[] args) {
        //非线程安全的map
        Map map = new HashMap<String, Integer>(1000 * 10);


        for (int i = 0; i < 10; i++) {
            Thread thread = new Runner(map);
            thread.start();

            //这个方法可以测试,线程安全时,Hashmap的大小最后能够达到多少
            // new Runner(map).run();
        }
    }

    static class Runner extends Thread {
        Map map;

        Runner(Map map) {
            this.map = map;
        }

        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                map.put(this.getName() + i, i);

                //线程安全的缓存HashMap
                Cache.put(this.getName() + i, i);
            }
            //如果是线程安全,那么HashMap的大小,最后能够达到1W.
            System.out.println("===非线程安全" + this.getName() + ": " + map.size());
            System.out.println("---线程安全" + this.getName() + ": " + Cache.size());

        }
    }
}
